const mongoose = require('mongoose');
const Comment = require('../model/comment.model');

/*新增*/
exports.create = function(req,res,next){
    const comment = new Comment(req.body);

    comment.save().then(data=>{
        res.json(data);
    });
}

/*修改*/
exports.update = function(req,res,next){
    const id = req.params.id;

    Comment.findByIdAndUpdate(id,{$set:req.body},{new:false})
    .then(data=>{
        res.json(data);
    });
}

/*删除*/
exports.remove = function(){
    const id = req.params.id;
    
    Comment.findByIdAndRemove(id,function(err,data){
        res.json({"message":"数据删除成功"});
    });
}

exports.removes = function(){
    const ids = req.body.ids;
    if(ids.lenth>0){
        Comment.remove({_id:{$in:ids}})
        .then(data=>{
            res.json({"message":"多条数据删除成功"});
        });
    }else{
        res.status(404).send({"msg":"没有选中记录"})
    }
}

/*查找*/
exports.list = function(req,res,next){
    var page = req.body.page || 1;
    var limit = req.body.rows || 5;
    
    var qcondition = {};

    if(req.body.comment){
        name = req.body.comment;
        qcondition = {
            "comment" : new RegExp(name,"i")
        }
    }

    Comment.paginate(qcondition,{page:+page,limit:+limit},function(err,result){
        if(result){
            var rows = result.docs;
            result.rows = rows;
            delete result.docs;
            res.json(result);
        }
    });
}  